﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ivi.Visa;
using NationalInstruments.Visa;

namespace Instruments
{
    public class Visa
    {
        public MessageBasedSession m_mbSession;
        public string _szDesc;
        public Visa(string szInsID)
        {
            using (var rmSession = new ResourceManager())
            {
                try
                {
                    m_mbSession = (MessageBasedSession)rmSession.Open(szInsID);
                    _szDesc = this.QueryType();
                }
                catch (Exception)
                {
                    _szDesc = "visa句柄创建失败！";
                }
            }
        }

        public void Write(string str)
        {
            if (m_mbSession == null)
                return;
            try
            {
                m_mbSession.RawIO.Write(str);
            }
            catch (Exception)
            {
                return;
            }
        }

        public string Read()
        {
            string szRet = "";
            if (null == m_mbSession)
                return string.Empty;
            try
            {
                szRet = m_mbSession.RawIO.ReadString();
            }
            catch (Exception)
            {
                return "Read failed.";
            }
            return szRet;
        }

        public string Query(string szQuestion)
        {
            string szRet = "";
            if (m_mbSession == null)
                return string.Empty;
            try
            {
                m_mbSession.RawIO.Write(szQuestion);
                szRet = m_mbSession.RawIO.ReadString();
            }
            catch (Exception)
            {
                return "Query failed, " + szQuestion;
            }
            return szRet;
        }

        public string QueryType()
        {
            return this.Query("*IDN?\n");
        }

        public void Clean()
        {
            this.Write("*CLS\n");
        }

        public void Reset()
        {
            this.Write("*RST\n");
        }

        ~Visa()
        {
            if (null != m_mbSession)
            {
                m_mbSession.Dispose();
            }
        }
    }
}
